﻿namespace LeastSquareMethod
{
    /// <summary>
    /// 用最小二乘法预测GDP
    /// </summary>
    internal class Program
    {
        static void Main(string[] args)
        {
            //利用最小二乘法计算出参数a，b
            int n = 61;
            double[] y = { 0.059716, 0.050057, 0.047209, 0.050707, 0.059708, 0.070436, 0.07672, 0.072882, 0.070847, 0.079706, 0.092603, 0.099801, 0.113688, 0.138544, 0.144182, 0.163432, 0.15394, 0.174938, 0.149541, 0.178281, 0.191149, 0.195866, 0.20509, 0.230687, 0.259947, 0.309488, 0.300758, 0.272973, 0.312354, 0.347768, 0.360858, 0.383373, 0.426916, 0.444731, 0.564325, 0.734548, 0.863747, 0.961604, 1.03, 1.09, 1.21, 1.34, 1.47, 1.66, 1.96, 2.29, 2.75, 3.55, 4.59, 5.1, 6.09, 7.55, 8.53, 9.57, 10.48, 11.06, 11.23, 12.31, 13.89, 14.28, 14.69, };
            double[] x = new double[61];
            x[0] = 1960;
            for (int i = 1; i < n; i++)
            {
                x[i] = x[i - 1] + 1;
            }
            double sumx = 0.0;
            double sumy = 0.0;
            double sumx2 = 0.0;
            double sumxy = 0.0;
            for (int i = 0; i < n; i++)
            {
                sumx += x[i];
                sumy += y[i];
                sumx2 += x[i] * x[i];
                sumxy += x[i] * y[i];
            }
            double averagex = sumx / n;
            double averagey = sumy / n;
            double b = (sumxy - n * averagex * averagey) / (sumx2 - n * averagex * averagex);
            double a = averagey - b * averagex;
            Console.WriteLine("请输入预测年份");
            double year = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine($"预测{year}年的GDP值为{b * year + a}万亿美元");
        }
    }
}